package completablefuture;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: callback
 * @author: WangPengPeng
 * @create: 2021-11-22 21:19
 **/
public class Demo3TheRun {

    static int forCount = 40;
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(15, 30, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(2000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        AtomicInteger counter = new AtomicInteger(0);
        CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            for (int i = 0; i < forCount; i++) {
                threadPoolExecutor.execute( new MyTask(counter));
            }
            return "this is result";
        }).thenRun(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("execution after task finish");
        });
        // 阻塞等待任务完成
        future.get();
        System.out.println("counter value : " + counter.get());
        while (counter.get() != forCount) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("current counter value : " + counter.get());
        }
        System.out.println("all finished");

    }
}
 class  MyTask implements Runnable {
    AtomicInteger counter;

    public MyTask(AtomicInteger counter) {
        this.counter = counter;

    }

    @Override
    public void run() {
        System.out.println("thread " + Thread.currentThread().getName() + " is running");
        counter.incrementAndGet();
        try {
            TimeUnit.SECONDS.sleep(60);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
